package com.zhangkunhao.notes.web.servlet;

import com.alibaba.fastjson.JSON;
import com.zhangkunhao.notes.entity.bo.Message;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

/**
 * 管理员的controller
 *
 * @author 20642
 */
@WebServlet("/administrator/*")
public class AdministratorServlet extends BaseDaoServlet {

    public void administratorLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收参数
        String parameter = request.getParameter("administratorAccount");
        String parameter1 = request.getParameter("administratorPassword");
        String administratorAccount = "";
        String administratorPassword = "";

        // 封装返回前端的对象
        Message<Object> administratorMessage = new Message<>(null, "管理员登录失败", 0);
        //判断
        if (parameter != null && parameter1 != null) {
            administratorAccount = new String(parameter.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            administratorPassword = new String(parameter1.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        } else {
            // 转换为json数据，写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(administratorMessage));
            return;
        }

        //2.校验管理员账户和密码
        if ("root".equals(administratorAccount)) {
            if ("123Aa!".equals(administratorPassword)) {
                //登录成功后使用session存数据
                HttpSession session = request.getSession();
                session.setAttribute("administratorAccount", administratorAccount);
                session.setAttribute("administratorPassword", administratorPassword);

                administratorMessage.setStatus(1);
                administratorMessage.setResult("管理员登录成功");
            } else {
                administratorMessage.setResult("密码错误");
            }
        } else {
            administratorMessage.setResult("账户错误");
        }

        System.out.println("administratorMessage:" + administratorMessage);

        // 3.转换为json数据，写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(administratorMessage));
    }
}
